package com.mindainfo.groundwave.server.base.component;

import com.alibaba.fastjson.JSONObject;
import com.mindainfo.groundwave.common.bean.CommonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by MD-01 on 2017/5/5.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public CommonResult<?> exception(HttpServletRequest request, Exception e){
        System.out.println("异常处理拦截");
        CommonResult result = new CommonResult();
        result.setCode(2);
        result.setErrMsg(e.getMessage());
        List<StackTraceElement> stacks = new ArrayList<>();
        StackTraceElement[] stackTraces = e.getStackTrace();
        for(StackTraceElement stackTrace : stackTraces){
            if(stackTrace.getClassName().startsWith("cn.bone")){
                stacks.add(stackTrace);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stackTraces",stacks);
        jsonObject.put("exceptionName",e.getClass().getName());
        result.setData(jsonObject);
        e.printStackTrace();
        return result;
    }
}
